#include "tithicompdialog.h"
#include "ui_tithicompdialog.h"
#include "computings.h"
#include <QFileDialog>


TithiCompDialog::TithiCompDialog(QWidget *parent) :
    QDialog(parent, Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint),
    ui(new Ui::TithiCompDialog)
{
    ui->setupUi(this);

    mTimeZone = 0;
}
//---------------------------

TithiCompDialog::~TithiCompDialog()
{
    delete ui;
}
//---------------------------
//---------------------------------------------------------------------------------


void TithiCompDialog::setProgramSettings(CProgramSettings& s)
{
    mTimeZone = s.TimeZone();
}
//---------------------------

void TithiCompDialog::on_CompPushButton_clicked()
{
    ui->CompPushButton->setDisabled(true);
    ui->plainTextEdit->clear();
    ui->plainTextEdit->repaint();

    QCursor normCursor = cursor();
    setCursor(Qt::WaitCursor);

    QList<CTithi> tithi;    
    QDateTime dt1 = QDateTime::currentDateTimeUtc(), dt2 = QDateTime::currentDateTimeUtc();
    dt2 = dt1;
    switch (ui->comboBox->currentIndex())
    {
    case 0:
        dt2 = dt2.addDays(30);
        break;
    case 1:
        dt2 = dt2.addDays(90);
        break;
    case 2:
        dt2 = dt2.addDays(180);
        break;
    case 3:
        dt2 = dt2.addYears(1);
        break;
    case 4:
        dt2 = dt2.addYears(2);
        break;
    case 5:
        dt2 = dt2.addYears(3);
        break;
    case 6:
        dt2 = dt2.addYears(5);
        break;
    case 7:
        dt2 = dt2.addYears(10);
        break;
    }

    tithi = SearchForTithi(dt1,dt2,mTimeZone);

    setCursor(normCursor);

    for (QList<CTithi>::iterator i = tithi.begin(); i < tithi.end(); ++i)
    {
        QString str;

        str = CTithi(*i).AsTithiStrExt();
        ui->plainTextEdit->appendPlainText(str);
    }

    QTextCursor textCursor = ui->plainTextEdit->textCursor();
    textCursor.movePosition(QTextCursor::Start);
    ui->plainTextEdit->setTextCursor(textCursor);
    ui->CompPushButton->setDisabled(false);
    ui->SavePushButton->setEnabled(true);
}
//---------------------------

void TithiCompDialog::on_SavePushButton_clicked()
{
    QString fn;
    QString fnf;

#ifdef Q_OS_WIN32
    fnf = "Текст (*.txt);;Все файлы (*.*)";
#endif

    fn = QFileDialog::getSaveFileName(this,"","",fnf);

    if (false == fn.isEmpty())
    {
        QFile f(fn);
        if (f.open(QIODevice::WriteOnly))
        {            
            QString str;

            str = ui->plainTextEdit->toPlainText();
            #ifdef Q_OS_WIN32
            str.replace("\n","\r\n");
            #endif

            f.write(str.toLocal8Bit());
            f.close();
        }
    }
}
//---------------------------
//---------------------------------------------------------------------------------
